import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qq_music/LyricsInformation.dart';
import 'package:qq_music/tools/NetWorkController.dart';
import 'package:qq_music/tools/PlayController.dart';
import 'package:qq_music/tools/extends/Json/SelectSond/QQ_music/select_sond.dart';

final playStateState = GlobalKey<_PlayStateState>();
final bvs = GlobalKey<_BottomViewState>();

AnimationController controller; //动画控制器

String songName = 'QQ音乐，让生活充满音乐';
DecorationImage coverImg =
    DecorationImage(image: NetworkImage('http://y.gtimg.cn/music/photo_new/T002R300x300M000004LJaz22RN4vs.jpg'));

// var coverImg = Image.asset('images/minIcon/defaultAlbumImage/defaultAlbumImage.png');
class BottomView extends StatefulWidget {
  BottomView({Key key}) : super(key: key);

  _BottomViewState createState() => _BottomViewState();
}

class _BottomViewState extends State<BottomView> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.push(
          context,
          new MaterialPageRoute(builder: (context) => new LyricsInformationMain()),
        );
      },
      child: Container(
        child: Column(
          children: [
            Container(
              height: ScreenUtil().setHeight(975.0),
            ),
            Container(
              child: Stack(
                children: <Widget>[
                  Container(
                    height: ScreenUtil().setHeight(101.0),
                  ),
                  new Container(
                    padding: EdgeInsets.only(top: 10.0),
                    width: ScreenUtil().setWidth(750),
                    child: Container(
                      decoration: BoxDecoration(border: Border(top: BorderSide(width: 1, color: Color(0xffe5e5e5)))),
                      height: ScreenUtil().setHeight(91.0),
                      /* color: Colors.grey[100], */
                      child: new Row(
                        children: [
                          new Expanded(
                            child: new Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                new Container(
                                  padding: const EdgeInsets.only(bottom: 8.0),
                                  margin: const EdgeInsets.only(left: 70.0, top: 13),
                                  child:
                                      /* new Text(
                                  songName,
                                  maxLines: 1,
                                  style: new TextStyle(
                                    fontWeight: FontWeight.bold,
                                  ),
                                ), */
                                      SizedBox(
                                    width: ScreenUtil().setWidth(400),
                                    child: Title(
                                      direction: Axis.horizontal,
                                      child: Text(
                                        songName,
                                        style: new TextStyle(
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                /* new Text(
                              'Kandersteg, Switzerland',
                              style: new TextStyle(
                                color: Colors.grey[500],
                              ),
                            ), */
                              ],
                            ),
                          ),
                          new Icon(
                            Icons.star,
                            color: Colors.red[500],
                          ),
                          new Text('41'),
                        ],
                      ),
                    ),
                  ),
                  /* Container(
                  height: ScreenUtil().setHeight(100.0),
                  width: ScreenUtil().setWidth(100.0),
                  margin: const EdgeInsets.only(left: 10.0),
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    image: coverImg,
                  ),
                ), */
                  Container(
                    height: ScreenUtil().setHeight(100.0),
                    width: ScreenUtil().setWidth(100.0),
                    margin: const EdgeInsets.only(left: 10.0),
                    child: SondImages(),
                  ),
                  PlayState(key: playStateState),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  bottomIconTitleEdit(Album album, String title) {
    String coverId = album.id.toString();
    String coverMid = album.mid.toString();
    print(coverId);
    String url;
    String get1;
    String get2 = coverId; //参数2
    if (coverId == '0') {
      url = "images/minIcon/defaultAlbumImage/defaultAlbumImage.png";
      setState(() {
        songName = title;
        coverImg = DecorationImage(image: ExactAssetImage(url));
      });

      controller.reset();
      controller.forward(); //向前播放动画
    } else {
      if (coverId[coverId.length - 2] == '0') {
        get1 = coverId[coverId.length - 1]; //参数1 这个参数 是 歌手id 的最后两位
      } else {
        get1 = coverId[coverId.length - 2] + coverId[coverId.length - 1]; //参数1 这个参数 是 歌手id 的最后两位
      }
      url = "http://imgcache.qq.com/music/photo/album_300/$get1/300_albumpic_${get2}_0.jpg";
      NetWorkController.get(url, (data) {
        try {
          //判断 网络的封面是否存在 不存在 执行第二个操作 获取封面
          if (data['error_code'] == 0 && data['response'] == null) {
            url = "http://y.gtimg.cn/music/photo_new/T002R300x300M000$coverMid.jpg";
          }
        } catch (e) {
          // 这跑出异常就证明 图片存在
        }
        setState(() {
          songName = title;
          coverImg = DecorationImage(image: NetworkImage(url));
        });
      }, parameter: {'data1': 'sdsada'});

      controller.reset();
      controller.forward(); //向前播放动画
    }
  }
}

class SondImages extends StatefulWidget {
  SondImages({Key key, this.title}) : super(key: key);
  final String title;

  @override
  State createState() => new _SondImages();
}

class _SondImages extends State<SondImages> with TickerProviderStateMixin {
  CurvedAnimation curved; //曲线动画，动画插值，

  @override
  void initState() {
    //初始化，当当前widget被插入到树中时调用
    super.initState();
    controller = new AnimationController(vsync: this, duration: const Duration(seconds: 30));
    curved = new CurvedAnimation(parent: controller, curve: Curves.linear); //模仿小球自由落体运动轨迹
    Tween(begin: 0.0, end: 2.0).animate(controller)
      //添加了状态监听
      ..addStatusListener((state) {
        //当动画结束时执行动画反转
        if (state == AnimationStatus.completed) {
          controller.reset();
          controller.forward();
          //当动画在开始处停止再次从头开始执行动画
        } else if (state == AnimationStatus.dismissed) {
          controller.reset();
          controller.forward();
        }
      });
    // controller.forward();
//    controller.forward();//放在这里开启动画 ，打开页面就播放动画
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
//        child: new FadeTransition(//透明度动画
//          opacity: curved,//将动画传入不同的动画widget
//          child: new FlutterLogo(//创建一个小部件，用于绘制Flutter��标
//            size: 200.0,
//          ),
//        ),
        child: new RotationTransition(
          //旋转动画
          turns: curved,
          child: Container(
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              image: coverImg,
            ),
          ),
        ),
      ),
      /* floatingActionButton: new FloatingActionButton(
        onPressed: () {
          setState(
            () {
              coverImg = Image.network('http://y.gtimg.cn/music/photo_new/T002R300x300M000004LJaz22RN4vs.jpg');
            },
          );
          controller.reset();
          controller.forward(); //向前播放动画
        },
        tooltip: 'fade',
        child: new Icon(Icons.track_changes),
      ), */
    );
  }
}
/* class PlayAndStop extends StatefulWidget {
  PlayAndStop({Key key}) : super(key: key);

  _PlayAndStopState createState() => _PlayAndStopState();
}

class _PlayAndStopState extends State<PlayAndStop> {
  @override
  Widget build(BuildContext context) {
    return Container(
       child: ,
    );
  }
}
 */

class PlayState extends StatefulWidget {
  PlayState({Key key}) : super(key: key);
  _PlayStateState createState() => _PlayStateState();
}

var playState = Icon(Icons.pause);
bool playStateBool = true;

class _PlayStateState extends State<PlayState> {
  double currentProgress = 0.0;
  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(110.0),
      child: new Container(
        padding: const EdgeInsets.only(bottom: 5.0),
        margin: const EdgeInsets.only(left: 275, top: 15),
        child: new GestureDetector(
          onTap: () {
            if (playStateBool == true) {
              setState(() {
                playState = Icon(Icons.play_arrow);
              });
              PlayController.pauseSond((data) {
                setState(() {
                  playStateBool = false;
                });
              });
            } else {
              PlayController.resumeSond((data) {
                setState(() {
                  playState = Icon(Icons.pause);
                  playStateBool = true;
                });
              });
            }
          },
          child: Stack(
            children: <Widget>[
              Positioned(
                child: new Row(
                  children: [
                    SizedBox(
                      width: 35,
                      height: 35,
                      child: CircularProgressIndicator(
                        value: currentProgress,
                        backgroundColor: Colors.brown,
                        valueColor: AlwaysStoppedAnimation(Colors.deepPurple),
                      ),
                    )
                  ],
                ),
              ),
              Positioned(
                //设置子元素
                child: playState,
                //设置定位，
                left: ScreenUtil().setWidth(11.0),
                top: ScreenUtil().setHeight(11.0),
              ),
            ],
          ),
        ),
      ),
    );
  }

  var _timer;
  void getPlaybackProgress(int totalLength) {
    //totalLength 总长度
    // _timer = new Timer.periodic(new Duration(seconds: 1), (timer) {
    PlayController.sondPlaybackProgress((data) {
      /* 当前播放时间 */
      if (data == 0) {
      } else {
        setState(() {
          currentProgress = data / totalLength;
        });
        if (currentProgress == 1) {
          print('播放ok');
        } else {}
      }
    });
    // });
  }

  cancelTimer() {
    _timer?.cancel();
  }
}

//文本滚动
class Title extends StatefulWidget {
  final Widget child;
  final Axis direction;
  final Duration animationDuration, backDuration, pauseDuration;

  Title({
    @required this.child,
    this.direction: Axis.horizontal,
    this.animationDuration: const Duration(milliseconds: 3000),
    this.backDuration: const Duration(milliseconds: 800),
    this.pauseDuration: const Duration(milliseconds: 800),
  });

  @override
  _TitleState createState() => _TitleState();
}

class _TitleState extends State<Title> {
  ScrollController scrollController = ScrollController();

  @override
  void initState() {
    scroll();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: widget.child,
      scrollDirection: widget.direction,
      controller: scrollController,
    );
  }

  void scroll() async {
    while (true) {
      await Future.delayed(widget.pauseDuration);
      await scrollController.animateTo(scrollController.position.maxScrollExtent,
          duration: widget.animationDuration, curve: Curves.easeIn);
      await Future.delayed(widget.pauseDuration);
      await scrollController.animateTo(0.0, duration: widget.backDuration, curve: Curves.easeOut);
    }
  }
}
